import { Button, Modal, Input, Tree, Icon, Avatar, Checkbox,message, Spin } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import React, {useState, useEffect} from 'react';
import { Scrollbars } from 'react-custom-scrollbars';
import styles from './index.less';
import { useRequest } from '@umijs/hooks';
import { getPaxType, getCheckedPaxType, addPaxType } from './service';
import AuthComponent from '@/components/Authorized/AuthComponent';

let arr = []
const VipPaxTypeMaintain = props => {

  const [current, setCurrent] = useState(1);
  const [keySearch, setKeySearch] = useState('');

  // 列表数据
  const [listData, handleListData] = useState([]) // 左侧待选列表

  // 控制勾选框
  const [checkAll, setCheckAll] = useState(false)
  const [indeterminate, setIndeterminate] = useState(true)
  // 贵宾列表（左边）---勾选的数据
  const[selectedItemIds, setSelectedItemIds] = useState([])
  const[selectedItems, setSelectedItems] = useState([])
  // 已选择列表（右边）
  const [targetItemIds, setTargetItemIds] = useState([])
  const [targetItems, setTargetItems] = useState([])

  // 按钮loading
  const [btnLoading, handleBtnLoading] = useState(false)

  //全部贵宾列表
  const {run: getAllList} = useRequest(() => getPaxType(), {
    manual: true,
    onSuccess: res => {
      handleListData(res)
    }
  })
  // 已选择贵宾列表
  const {run: getCheckedList} = useRequest(() => getCheckedPaxType(), {
    manual: true,
    onSuccess: res => {
      if (res.length > 0) {
        setTargetItems(res)
        setTargetItemIds(res.map(item => {return item.paxTypeCode}))
      } else {
        setTargetItems([])
        setTargetItemIds([])
      }
    }
  })

  useEffect(()=> {
    getAllList()
    getCheckedList()
  },[])

  // 全选/反选
  const handleCheckAllItem = (e) =>{
    if (e.target.checked) {
      setSelectedItems(listData)
      setSelectedItemIds(listData.map(item => {return item.paxTypeCode}))
      setIndeterminate(false)
    } else {
      setSelectedItemIds([])
      setSelectedItems([])
      setIndeterminate(true)
    }
  }

  // 点击左侧列表
  const changeItem = val => {
    if (!~selectedItemIds.indexOf(val.paxTypeCode)){
      setSelectedItemIds(pre => [val.paxTypeCode].concat(pre))
      setSelectedItems(pre => [val].concat(pre))
    } else {
      setSelectedItemIds(pre => pre.filter(paxTypeCode => paxTypeCode !== val.paxTypeCode))
      setSelectedItems(pre => pre.filter(item => item.paxTypeCode !== val.paxTypeCode))
    }
      
  }
  // 把左边列表添加到右边去
  const chooseToSelect = () => {
    setTargetItemIds(pre => ([...new Set([...pre, ...selectedItemIds])]))

    let newobj = {}
    let uniqueArray = [...targetItems, ...selectedItems] .reduce((preVal, curVal) => {
      newobj[curVal.paxTypeCode] ? '' : newobj[curVal.paxTypeCode] = preVal.push(curVal); 
      return preVal 
    }, [])
    setTargetItems(uniqueArray)

    setSelectedItemIds([])
    setSelectedItems([])
  }
  // 点击右侧已选列表
  const closeItem = (id) => {
    setTargetItemIds(pre => pre.filter(paxTypeCode => paxTypeCode !== id))
    setTargetItems(pre => pre.filter(item => item.paxTypeCode !== id))
  }

  // 确认添加
  const sureDept = () => {
    let arrData = []
    if (targetItems.length === 0) {
      message.error("请选择贵宾")
    } else {
      const hide = message.loading('正在提交')
      targetItems.map(item => {
        arrData.push({
          typeCode: item.paxTypeCode,
          typeName: item.paxTypeName
        })
      })

      addPaxType(arrData).then(res=>{
        if (res.code === '0') {
          hide()
          getCheckedList()
          setTimeout(() => {
            message.success('保存贵宾旅客类别成功')
          }, 1000);
        } else {
          hide()
          setTimeout(() => {
            message.error('提交有误，请重试')
          }, 1000);
        }
      })
    }
  }
  const cancel = () => {
    setSelectedItemIds([])
    setSelectedItems([])
    getCheckedList()
  }

  return (
      <div className={styles.vipPaxTypeMaintain}>
        <div className={styles.title}>
          <span  style={{ paddingRight: 10, fontWeight: 'bold', color: '#000',fontSize:"16px" }}>贵宾旅客类别维护</span>
        </div>
        <div className={styles.container}>
          <div className={styles.left}>
            <div className={styles.content}>
              <div className={styles.listOp}>
                <Checkbox 
                  indeterminate={!!selectedItems.length && selectedItems.length < listData.length}
                  checked={selectedItems.length === listData.length}
                  onChange={handleCheckAllItem}>{selectedItems.length}/{listData.length}项</Checkbox>
                <span>旅客类别</span>
              </div>
              <Scrollbars autoHide style={{height: "100%", width: "100%"}}>
                  {listData.length > 0 && listData.map(v=>{
                    return (
                      <div onClick={() => changeItem(v)} style={{paddingTop: '10px'}} className={styles.itemLeft}>
                        <div className={styles.itemCheck}>
                          <span className={` ${~selectedItemIds.indexOf(v.paxTypeCode)  ? styles.active : ''}`}>
                            {~selectedItemIds.indexOf(v.paxTypeCode) ? <Icon type="check" /> : null}
                          </span>
                        </div>
                        <div className={styles.personInfo}>
                          <span>{v.paxTypeName}</span>
                        </div>
                      </div>
                    )
                  })}
                </Scrollbars>
            </div>
          </div>
          <div className={styles.middle}>
            <Button type="primary" disabled={selectedItems.length===0} onClick={()=>{chooseToSelect()}}> ＞ </Button>
          </div>
          
          <div className={styles.right}>
            <div className={styles.listOp}>
                <span>{targetItemIds? targetItemIds.length: '0'}项</span>
                <span>贵宾旅客类别</span>
            </div>
            <div className={styles.content}>
              <Scrollbars autoHide style={{height: "100%", width: "100%"}}>
                {targetItems.length > 0 && targetItems.map(v=>{
                  return (
                    <div style={{paddingTop: '10px'}} className={styles.itemRight}>
                      <span>{v.paxTypeName}</span>
                      <span onClick={() => {closeItem(v.paxTypeCode)}} style={{cursor: 'pointer', width: '30px', height: '20px', textAlign: 'center'}} className={styles.checkT}>
                        <DeleteOutlined />
                      </span>
                    </div>
                  )
                })}
              </Scrollbars>
            </div>
          </div>
        </div>
        <div className={styles.btn}>
          <Button loading={btnLoading} onClick={()=>{cancel()}}>取消</Button>
          &nbsp;&nbsp;
          <AuthComponent authCode="vipRoom.paxTypeMain.sure">
            <Button onClick={()=>{sureDept()}} type="primary" loading={btnLoading}>确定</Button>
          </AuthComponent>
        </div>
      </div>
  )
}

export default VipPaxTypeMaintain;
